package com.nisco.ampf;

import java.util.ArrayList;
import java.util.HashMap;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.nisco.ampf.util.ConstString;
import com.nisco.ampf.util.DateSwitch;
import com.nisco.ampf.util.HttpThread;
import com.nisco.ampf.util.MyListViewAdapter;
import com.nisco.ampf.util.MyListViewAdapter.ViewHolder;
import com.nisco.ampf.util.WebServerConn;

public class StackManagerActivity extends Activity {

	private ListView stackList;
	private Button searchBtn;
	private Button cameraSearch;
	private Button changeSatckBtn;
	private EditText stackLoc_oldEdit;
	private EditText plateNo_oldEdit;
	private EditText stackLoc_newEdit;
	private TextView searchStateTxt;
	private String[] list = null;
	private String loginName;
	WebServerConn serverConn;
	DateSwitch dateSwitch;
	ArrayList<HashMap<String, Object>> arrayList = null;
	MyListViewAdapter myListViewAdapter;
	ViewHolder viewHolder;
	ProgressDialog myDialog = null;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.moveplate_main);
		Intent intent = getIntent();
		if (intent.hasExtra(ConstString.LOGINID)) {
			loginName = intent.getStringExtra(ConstString.LOGINID);
		}
		stackList = (ListView) findViewById(R.id.stackList);
		searchBtn = (Button) findViewById(R.id.stackSerBtn);
		cameraSearch = (Button) findViewById(R.id.cameraSearch);
		changeSatckBtn = (Button) findViewById(R.id.changeSatckBtn);
		stackLoc_oldEdit = (EditText) findViewById(R.id.stackLoc_oldEdit);
		plateNo_oldEdit = (EditText) findViewById(R.id.plateNo_oldEdit);
		stackLoc_newEdit = (EditText) findViewById(R.id.stackLoc_newEdit);
		searchStateTxt = (TextView) findViewById(R.id.searchStateTxt);
		searchBtn.setOnClickListener(new btnClickListener());
		changeSatckBtn.setOnClickListener(new btnClickListener());
		cameraSearch.setOnClickListener(new btnClickListener());
		stackList.setOnItemClickListener(new OnItemClickListener() {

			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {
				showDetail(arg1, arg2);
			}
		});
	}

	/**
	 * 显示listview中item的详细信息
	 * 
	 * @param arg1
	 * @param arg2
	 */
	private void showDetail(View arg1, int arg2) {
		viewHolder = (ViewHolder) arg1.getTag();

		AlertDialog.Builder builder = new Builder(StackManagerActivity.this);

		builder.setTitle("详细信息").setMessage(
				"垛位号：" + arrayList.get(arg2).get("YARD_ADDR").toString()
						+ "\n垛    层："
						+ arrayList.get(arg2).get("BED_SEQ").toString()
						+ "\n钢板号："
						+ arrayList.get(arg2).get("PLATE_NO").toString()
						+ "\n状    态："
						+ arrayList.get(arg2).get("PROC_CD").toString()
						+ "\n标准号："
						+ arrayList.get(arg2).get("APLY_STDSPEC").toString()
						+ "\n厚    度："
						+ arrayList.get(arg2).get("THK").toString()
						+ "\n宽    度："
						+ arrayList.get(arg2).get("WID").toString()
						+ "\n长    度："
						+ arrayList.get(arg2).get("LEN").toString()
						+ "\n重    量："
						+ arrayList.get(arg2).get("WGT").toString());
		builder.setPositiveButton("确认",
				new android.content.DialogInterface.OnClickListener() {

					public void onClick(DialogInterface arg0, int arg1) {
						arg0.dismiss();

					}
				});
		AlertDialog dialog = builder.create();
		dialog.setCanceledOnTouchOutside(true);
		dialog.show();
	}

	/**
	 * button监听事件
	 * 
	 * @author Robin
	 * 
	 */
	class btnClickListener implements OnClickListener {

		public void onClick(View v) {
			switch (v.getId()) {
			case R.id.stackSerBtn:// 查询

				String oldStackloc = "";
				String oldPlateNo = "";
				oldStackloc = stackLoc_oldEdit.getText().toString()
						.toUpperCase();
				oldPlateNo = plateNo_oldEdit.getText().toString().toUpperCase();
				HttpThread httpThread = new HttpThread(handler);
				if (!oldPlateNo.equals("") || !oldStackloc.equals("")) {
					// searchStateTxt.setText("查询为空,输入正确的查询条件！");
					// serverConn = new WebServerConn();
					httpThread.doStart(StackManagerActivity.this, oldStackloc,
							oldPlateNo, "queryStack");
					// list = serverConn.queryStack(oldStackloc, oldPlateNo);
					// dateSwitch = new DateSwitch();
					// arrayList = dateSwitch.stringToMap(list);
					// if (arrayList == null) {
					// stackList.setAdapter(null);
					// searchStateTxt.setText("查询为空,输入正确的查询条件！");
					// } else {
					// myListViewAdapter = new MyListViewAdapter(
					// StackManagerActivity.this, arrayList);
					// stackList.setAdapter(myListViewAdapter);
					// searchStateTxt.setText("查询成功,共" + arrayList.size()
					// + "条数据！");
					// }
				} else {
					stackList.setAdapter(null);
					searchStateTxt.setText("无查询条件！");
				}
				break;
			case R.id.changeSatckBtn:// 倒垛
				if (arrayList == null) {
					Toast.makeText(StackManagerActivity.this,
							"请先查询数据！", Toast.LENGTH_LONG).show();
				} else {
					serverConn = new WebServerConn();
					if (stackLoc_newEdit.getText().toString().length() == 0) {
						Toast.makeText(StackManagerActivity.this, "请填写新的垛号！",
								Toast.LENGTH_LONG).show();
					} else {
						String changeStackStr = "";
						String responseStr = "";
						if ((myListViewAdapter.selectArrayList).isEmpty()) {
							Toast.makeText(StackManagerActivity.this,
									"请至少选择一项进行倒垛！", Toast.LENGTH_LONG).show();
						} else {
							changeStackStr = dateSwitch.arrayListToString(
									myListViewAdapter.selectArrayList,
									ConstString.PLATE_NO);
							responseStr = serverConn.changeStack(
									changeStackStr, stackLoc_newEdit.getText()
											.toString().toUpperCase(),
									loginName, ConstString.SERVICE_PLATE);
							if (responseStr.equals(ConstString.RETURNSTR)) {
								Toast.makeText(StackManagerActivity.this,
										"倒垛成功！", Toast.LENGTH_SHORT).show();
								// 倒垛成功后重新装载listview 两个条件都要传（跺号，钢板号）
								list = serverConn.queryStack(stackLoc_oldEdit
										.getText().toString().toUpperCase(),
										plateNo_oldEdit.getText().toString()
												.toUpperCase());
								arrayList = dateSwitch.stringToMap(list);
								if (arrayList == null) {
									stackList.setAdapter(null);
									searchStateTxt.setText("查询为空,输入正确的查询条件！");
								} else {
									myListViewAdapter = new MyListViewAdapter(
											StackManagerActivity.this,
											arrayList);
									stackList.setAdapter(myListViewAdapter);
									searchStateTxt.setText("查询成功,共"
											+ arrayList.size() + "条数据！");
								}
							} else {
								System.out.println(responseStr);
								Toast.makeText(StackManagerActivity.this,
										responseStr, Toast.LENGTH_LONG).show();
							}
						}
					}
				}
				break;
			case R.id.cameraSearch:
				Intent intent = new Intent(StackManagerActivity.this,
						CaptureActivity.class);
				startActivityForResult(intent, 1);

				break;
			default:
				break;
			}
		}
	}

	/**
	 * 捕获消息队列,在线程运行的同时
	 */
	Handler handler = new Handler() {
		public void handleMessage(Message m) {
			String[] s = m.getData().getStringArray("data");
			if (s != null) {
				list = s;
				dateSwitch = new DateSwitch();
				arrayList = dateSwitch.stringToMap(list);
			}
			if (arrayList == null) {
				stackList.setAdapter(null);
				searchStateTxt.setText("查询为空,输入正确的查询条件！");
			} else {
				myListViewAdapter = new MyListViewAdapter(
						StackManagerActivity.this, arrayList);
				stackList.setAdapter(myListViewAdapter);
				searchStateTxt.setText("查询成功,共" + arrayList.size() + "条数据！");
			}
		}
	};

	/**
	 * 重写onActivityResult()来处理子Activity返回的数据
	 */
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		switch (resultCode) {
		case RESULT_OK:

			Bundle b = data.getExtras();

			String str = b.getString(ConstString.CAMERA_RESULT);
			plateNo_oldEdit.setText(str);
			// 扫描完成后自动查询
			serverConn = new WebServerConn();
			list = serverConn.queryStack("", str);
			dateSwitch = new DateSwitch();
			arrayList = dateSwitch.stringToMap(list);
			if (arrayList == null) {
				stackList.setAdapter(null);
				searchStateTxt.setText("查询为空,输入正确的查询条件！");
			} else {
				myListViewAdapter = new MyListViewAdapter(
						StackManagerActivity.this, arrayList);
				stackList.setAdapter(myListViewAdapter);
				searchStateTxt.setText("查询成功,共" + arrayList.size() + "条数据！");
			}
			break;

		default:

			break;

		}
	}

	/**
	 * 文本框监听事件
	 * 
	 * @author Robin
	 * 
	 */
	class txtChangeListener implements TextWatcher {

		public void afterTextChanged(Editable s) {
			String temp = s.toString();
			String tem = temp.substring(temp.length() - 1, temp.length());
			char[] temC = tem.toCharArray();
			int mid = temC[0];
			// 数字
			if (mid >= 48 && mid <= 57) {
				return;
			}
			// 大写字母
			if (mid >= 65 && mid <= 90) {
				return;
			}
			// 小写字母
			if (mid >= 97 && mid <= 122) {
				return;
			}
			// 特殊字符 -、 \ 、/
			if (mid == 45 || mid == 47 || mid == 92) {
				return;
			}
			s.delete(temp.length() - 1, temp.length());

		}

		public void beforeTextChanged(CharSequence s, int start, int count,
				int after) {

		}

		public void onTextChanged(CharSequence s, int start, int before,
				int count) {

		}
	}
}
